<template>
  <div>
    <Breadcrumb :titles="pathTitles"></Breadcrumb>
    <el-card class="box-card">
      <el-row class="role-top">
        <el-col :span="8">
          <el-input placeholder="请输入内容角色名">
            <el-button slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="8" :offset="1">
          <el-button type="primary" @click="addRole">添加角色</el-button>
        </el-col>
      </el-row>
      <RoleTable :roles="roles" @roleUpdateClick="roleUpdateClick"></RoleTable>
    </el-card>
    <el-dialog
      :title="`更新${updateRole.name}角色的权限`"
      :visible.sync="roleRightUpdateDialogVisible"
      width="50%"
      @close="showPermissionDialogClose"
    >
      <el-tree
        ref="showPermissionTreeRef"
        :data="permissonsTree"
        show-checkbox
        node-key="id"
        :props="permissonsProps"
        :default-expanded-keys="defaultExpandedEeys"
      >
      </el-tree>

      <span slot="footer" class="dialog-footer">
            <el-button @click="roleRightUpdateDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="sureUpdateRolePermissions">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="添加角色"
      :visible.sync="addRoleDialogVisible"
      width="50%"
      @close="addRoleDialogClose"
    >
      <el-form ref="addRoleDialogForm" :model="addRoleData" :rules="userRules">
        <el-form-item label-width="80px" label="角色名" prop="rolename">
          <el-input placeholder="角色名" v-model="addRoleData.rolename">
          </el-input>
        </el-form-item>
        <el-form-item label-width="80px" label="角色描述">
          <el-input placeholder="角色描述" v-model="addRoleData.desc">
          </el-input>
        </el-form-item>
      </el-form>
      <div>
        <label class="el-form-item__label" style="width: 120px;">请选择角色权限</label>
      </div>
      <el-row>
        <el-col :span="20" :offset="3">
          <el-tree
            ref="addRoleTreeRef"
            :data="permissonsTree"
            show-checkbox
            node-key="id"
            :props="permissonsProps"
          >
          </el-tree>
        </el-col>
      </el-row>

      <span slot="footer" class="add-role-dialog-footer">
            <el-button @click="addRoleDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addRoleClick">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

  import Breadcrumb from 'components/content/Breadcrumb';

  import getPathTitleMixin from "mixin/getPathTitleMixin";

  import RoleTable from './components/RoleTable';

  import {roles,rolePermissions,permissons,updateRolePermissions,addRolePermission} from "network/permission/PermissionRequest";

  export default {
    name: "RoleList",
    mixins:[getPathTitleMixin],
    data:function(){

      return {

        roles:[],
        roleRightUpdateDialogVisible:false,
        addRoleDialogVisible:false,
        updateRole:{},
        permissonsTree:null,
        permissonsProps:{
          children:'children',
          label:'name'
        },
        defaultExpandedEeys:[],
        leafPermissionIds:[],
        addRoleData:{
          rolename:'',
          desc:'',
          permissionids:''
        },
        userRules:{
          rolename:{required:true, message:'请输入角色名',trigger:'blur'}
        }
      }
    },
    components:{
      Breadcrumb,
      RoleTable
    },
    created() {

      this.loadRoleListData();
    },
    methods:{

      async loadRoleListData(){

        this.roles = await roles();

      },
     async roleUpdateClick(row){

          this.updateRole = row;

          if (row.children === undefined){

              row.children = await rolePermissions({
                roleid:row.id
              });
          }

         if (row.children.length > 0){

           // 获取子节点
           this.getLeafPermissions(row.children,this.leafPermissionIds);
         }

          if (this.permissonsTree === null){

            this.permissonsTree = await permissons({
              'type':1
            });

          }


         this.$nextTick(()=>{

             this.$refs.showPermissionTreeRef.setCheckedKeys(this.leafPermissionIds);
             this.defaultExpandedEeys = this.leafPermissionIds;

         });
         this.roleRightUpdateDialogVisible = true;

      },
      showPermissionDialogClose(){

        this.leafPermissionIds = [];
        this.defaultExpandedEeys = [];
      },
      addRoleDialogClose(){

        this.$refs.addRoleDialogForm.resetFields();
      },
      sureUpdateRolePermissions(){


        const halfCheckedKeys = this.$refs.showPermissionTreeRef.getHalfCheckedKeys();
        const checkedKeys = this.$refs.showPermissionTreeRef.getCheckedKeys();
        const updatePermissionStr = [...halfCheckedKeys,...checkedKeys].join(',');

        updateRolePermissions({
          roleid:this.updateRole.id,
          permissionids:updatePermissionStr
        }).then(data=>{

          this.roleRightUpdateDialogVisible = false;
          this.loadRoleListData();

        }).catch(error=>{

        });

      },
      getLeafPermissions(children,arr){

        if (children === undefined){

          return arr;
        }

        children.forEach(child=>{

          if (child.children === undefined){

            arr.push(child.id);
          }else if (child.children instanceof Array) {

            this.getLeafPermissions(child.children,arr);
          }

        });
      },
      async addRole(){

        if (this.permissonsTree === null){

          try {

            this.permissonsTree = await permissons({
              'type':1
            });
            this.addRoleDialogVisible = true;
          }catch (e) {

          }


        }

      },
      addRoleClick(){

        this.$refs.addRoleDialogForm.validate(data=>{

          if (data !== true){

            return;
          }

          const halfCheckedKeys = this.$refs.addRoleTreeRef.getHalfCheckedKeys();
          const checkedKeys = this.$refs.addRoleTreeRef.getCheckedKeys();
          this.addRoleData.permissionids = [...halfCheckedKeys,...checkedKeys].join(',');

          this.addRoleSend(this.addRoleData);
        });
      },
      async addRoleSend(params){

        try {

          await addRolePermission(params);
          this.addRoleData.permissionids = '';
          this.addRoleDialogVisible = false;
          this.loadRoleListData();

        }catch (e) {

          console.log(e);
        }


      }
    }
  }
</script>

<style scoped>

  .role-top{
    margin-bottom: 20px;
  }

</style>
